import router from './router'
import {arrIsSame} from '@/utils/filters'
// import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import Cookie from 'js-cookie'
import store from '@/store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 不重定向白名单
const whiteList = ['/login', '/auth-redirect']

const whiteNext = ['/dashboard', '/']

let getFirstUrl = () => {
    let roles = JSON.parse(localStorage.getItem('rolesCode'))
    let url = ''
    router.options.routes.forEach(item => {
        if (Boolean(item.meta) && Boolean(item.meta.code) && Boolean(roles.includes(item.meta.code)) && Boolean(item.children.length) && Boolean(!url)) {
            item.children.forEach(it => {
                if (Boolean(it.meta) && Boolean(it.meta.code) && Boolean(roles.includes(it.meta.code)) && Boolean(!url)) {
                    url = item.path + '/' + it.path
                }
            })
        }
    })
    return url
}
router.beforeEach(async (to, from, next) => {
    next()
    // 进度条开始
    NProgress.start()
    if (Cookie.get('token')) {
        // 如果当前页面是仪表板，则在每次挂接后都不会触发，请手动处理它
        if (to.path === '/dashboard' || to.path === '/' || to.path === '/login') {
            next(getFirstUrl())
        }
        if (!sessionStorage.getItem('lastRequest') || new Date().getTime() - sessionStorage.getItem('lastRequest') > 1800000) {
            let oldRole = JSON.parse(localStorage.getItem('rolesCode'))
            store.dispatch('user/getUserInfoAgain').then(res => {
                if (res[1].code.toString() === '200') {
                    // 返回前已经重组权限列表并存储
                    if (!arrIsSame(JSON.parse(oldRole), JSON.parse(localStorage.getItem('rolesCode')))) {
                        store.dispatch('user/updateReRender')
                    }
                }
                // 判断非白名单的无权限地址、判断权限code（code需要存在，会有无code的页面，就是不需要权限）、判断不是9999超管用户
                if (!whiteNext.includes(to.path) && localStorage.getItem('rolesCode').indexOf(to.meta.code) === -1 && to.meta.code) {
                    Cookie.set('timeOut', 'timeOut')
                    store.dispatch('user/logout').then(() => {
                        window.location.href = '/login'
                    })
                } else {
                    next()
                }
            }).catch(() => {
                // 判断非白名单的无权限地址、判断权限code（code需要存在，会有无code的页面，就是不需要权限）、判断不是9999超管用户
                if (!whiteNext.includes(to.path) && localStorage.getItem('rolesCode').indexOf(to.meta.code) === -1 && to.meta.code) {
                    Cookie.set('timeOut', 'timeOut')
                    store.dispatch('user/logout').then(() => {
                        window.location.href = '/login'
                    })
                } else {
                    next()
                }
            })
        } else {
            // 判断非白名单的无权限地址、判断权限code（code需要存在，会有无code的页面，就是不需要权限）、判断不是9999超管用户
            if (!whiteNext.includes(to.path) && localStorage.getItem('rolesCode').indexOf(to.meta.code) === -1 && to.meta.code) {
                Cookie.set('timeOut', 'timeOut')
                store.dispatch('user/logout').then(() => {
                    window.location.href = '/login'
                })
            } else {
                next()
            }
        }
    } else {
        if (!whiteList.includes(to.path)) {
            Cookie.set('timeOut', 'timeOut')
            store.dispatch('user/logout').then(() => {
                window.location.href = '/login'
            })
        } else {
            next()
        }
    }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})
